package net.sk.china.city.service.impl;

import net.sk.china.city.utils.DateUtils;
import net.sk.china.city.utils.SecurityUtils;
import net.sk.china.common.exception.ServiceException;
import net.sk.china.city.utils.PlatformIdHolder;
import lombok.Synchronized;
import net.sk.china.city.domain.*;
import net.sk.china.city.domain.dto.user.UserUpdateDTO;
import net.sk.china.city.domain.vo.ArExchangeDetailVo;
import net.sk.china.city.domain.vo.ArExchangeItemVO;
import net.sk.china.city.domain.vo.ArExchangeVO;
import net.sk.china.city.domain.vo.SpecificationsVO;
import net.sk.china.city.mapper.*;
import net.sk.china.city.service.IArExchangeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 兑换记录Service业务层处理
 *
 * @author gxf
 * @date 2024-04-12
 */
@Service
public class ArExchangeServiceImpl implements IArExchangeService {
    @Autowired
    private ArExchangeMapper arExchangeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArExchangeItemMapper arExchangeItemMapper;

    @Autowired
    private ArExchangeLocationMapper arExchangeLocationMapper;

    @Autowired
    private ArSupermarketProductMapper arSupermarketProductMapper;

    @Autowired
    private ArInventoryMapper arInventoryMapper;


    /**
     * 查询兑换记录
     *
     * @param id 兑换记录主键
     * @return 兑换记录
     */
    @Override
    public ArExchangeVO selectArExchangeById(Long id) {
        return arExchangeMapper.selectArExchangeById(id);
    }

    /**
     * 查询兑换记录列表
     *
     * @return 兑换记录
     */
    @Override
    public List<ArExchangeDetailVo> selectArExchangeList(ArExchangeVO arExchangeVo) {
        arExchangeVo.setPlatformId(PlatformIdHolder.getPlatformId());
        List<ArExchangeVO> arExchangeVOS = arExchangeMapper.selectArExchangeList(arExchangeVo);
        List<ArExchangeDetailVo> arExchangeDetailVos = new ArrayList<>();

        for (ArExchangeVO arExchangeVO : arExchangeVOS) {
            ArExchangeDetailVo arExchangeDetailVo = new ArExchangeDetailVo();
            BeanUtils.copyProperties(arExchangeVO,arExchangeDetailVo);
            ArExchangeItem arExchangeItem = new ArExchangeItem();
            arExchangeItem.setExchangeId(arExchangeVO.getId());
            List<ArExchangeItem> arExchangeItems = arExchangeItemMapper.selectArExchangeItemList(arExchangeItem);
            List<ArExchangeItemVO> arExchangeItemVOS = new ArrayList<>();
            for (ArExchangeItem exchangeItem : arExchangeItems) {
                SpecificationsVO specificationsVO = new SpecificationsVO();
                specificationsVO.setColor(exchangeItem.getColor());
                specificationsVO.setSize(exchangeItem.getSize());
                specificationsVO.setSpecifications(exchangeItem.getSpecifications());
                ArExchangeItemVO arExchangeItemVO = new ArExchangeItemVO();
                BeanUtils.copyProperties(exchangeItem,arExchangeItemVO);
                arExchangeItemVO.setSpecification(specificationsVO);
                arExchangeItemVOS.add(arExchangeItemVO);
            }
            arExchangeDetailVo.setArExchangeItemVOs(arExchangeItemVOS);

            arExchangeDetailVos.add(arExchangeDetailVo);
        }
        return arExchangeDetailVos;
    }

    /**
     * 查询简单兑换记录列表
     *
     * @return
     */
    @Override
    public List<ArExchangeVO> selectSimpleArExchangeList() {
        List<ArExchangeVO> arExchangeVOS = arExchangeMapper.selectArExchangeList(null);
        for (ArExchangeVO arExchangeVO : arExchangeVOS) {
            if (arExchangeVO.getExchangeStatus().equals("0"))
                arExchangeVO.setExchangeStatusName("待取");
            else {
                arExchangeVO.setExchangeStatusName("已取");
            }
        }
        return arExchangeVOS;
    }

    /**
     * 新增兑换记录
     *
     * @param arExchange 兑换记录
     * @return 结果
     */
    @Override
    public int insertArExchange(ArExchange arExchange) {
        arExchange.setPlatformId(PlatformIdHolder.getPlatformId());
        arExchange.setCreateTime(LocalDate.now());
        return arExchangeMapper.insertArExchange(arExchange);
    }

    /**
     * 修改兑换记录
     *
     * @param arExchange 兑换记录
     * @return 结果
     */
    @Override
    public int updateArExchange(ArExchange arExchange) {
        arExchange.setUpdateTime(LocalDate.now());
        return arExchangeMapper.updateArExchange(arExchange);
    }

    /**
     * 批量删除兑换记录
     *
     * @param ids 需要删除的兑换记录主键
     * @return 结果
     */
    @Override
    public int deleteArExchangeByIds(Long[] ids) {
        return arExchangeMapper.deleteArExchangeByIds(ids);
    }

    /**
     * 删除兑换记录信息
     *
     * @param id 兑换记录主键
     * @return 结果
     */
    @Override
    public int deleteArExchangeById(Long id) {
        return arExchangeMapper.deleteArExchangeById(id);
    }

    /**
     * 获取当天10条兑换记录，按兑换时间倒序
     *
     * @return
     */
    @Override
    public List<ArExchangeDetailVo> getAllExchange() {
        LocalDate today = LocalDate.now();
        // 设置时间为当天的 0 点
        LocalDateTime midnight = today.atStartOfDay();
        // 获取当天 0 点的时间戳（秒）
        long timestamp = midnight.toEpochSecond(ZoneOffset.ofHours(8));
        ArExchangeVO arExchangeVO1 = new ArExchangeVO();
        arExchangeVO1.setUpdateTime(LocalDate.ofEpochDay(timestamp));
        arExchangeVO1.setPlatformId(PlatformIdHolder.getPlatformId());
        List<ArExchangeVO> arExchangeVOS = arExchangeMapper.selectArExchangeList(arExchangeVO1);

        //截取十条
        int i = 1;
        List<ArExchangeDetailVo> arExchangeDetailVos = new ArrayList<>();
        for (ArExchangeVO arExchangeVO : arExchangeVOS) {
            if (Objects.equals(arExchangeVO.getExchangeStatus(), "0"))
                continue;
            if (i > 10)
                break;
            i++;
            //转为detail
            ArExchangeDetailVo arExchangeDetailVo = new ArExchangeDetailVo();
            BeanUtils.copyProperties(arExchangeVO, arExchangeDetailVo);

            //detail添加兑换项列表
            ArExchangeItem arExchangeItem = new ArExchangeItem();
            arExchangeItem.setExchangeId(arExchangeVO.getId());
            List<ArExchangeItem> arExchangeItems = arExchangeItemMapper.selectArExchangeItemList(arExchangeItem);

            List<ArExchangeItemVO> arExchangeItemVOS = new ArrayList<>();
            for (ArExchangeItem exchangeItem : arExchangeItems) {
                //兑换项转为VO
                ArExchangeItemVO arExchangeItemVO = new ArExchangeItemVO();
                BeanUtils.copyProperties(exchangeItem, arExchangeItemVO);
                String size = exchangeItem.getSize();
                String color = exchangeItem.getColor();
                String specifications = exchangeItem.getSpecifications();

                arExchangeItemVO.setSpecification(color, size, specifications);
                arExchangeItemVOS.add(arExchangeItemVO);
            }
            arExchangeDetailVo.setArExchangeItemVOs(arExchangeItemVOS);

            arExchangeDetailVos.add(arExchangeDetailVo);
        }
        return arExchangeDetailVos;
    }

    /**
     * 现场兑换
     *
     * @param arExchangeDetailVo
     */
    @Override
    @Synchronized
    @Transactional(rollbackFor = Exception.class)
    public void exchange(ArExchangeDetailVo arExchangeDetailVo) {
        ArExchange arExchange = new ArExchange();
        Long userId = arExchangeDetailVo.getUserId();
        arExchange.setUserId(userId);
        arExchange.setExchangeStatus("1");
        Long locationId = arSupermarketProductMapper.selectArSupermarketProductById(arExchangeDetailVo.getArExchangeItemVOs().get(0).getProductId()).getLocationId();
        ArExchangeLocation arExchangeLocation = arExchangeLocationMapper.selectArExchangeLocationById(locationId);
        arExchange.setExchangeLocation(arExchangeLocation.getExchangeLocation());
        arExchange.setTotalPrice(arExchangeDetailVo.getTotalPrice());
        arExchange.setPhone(arExchangeLocation.getPhone());
        arExchange.setUpdateTime(LocalDate.now());
        arExchange.setCreateTime(LocalDate.now());
        arExchange.setPlatformId(PlatformIdHolder.getPlatformId());
        //添加兑换
        if (arExchangeMapper.insertArExchange(arExchange) == 0)
            throw new ServiceException("兑换失败");

        for (ArExchangeItemVO arExchangeItemVO : arExchangeDetailVo.getArExchangeItemVOs()) {
            ArExchangeItem arExchangeItem = new ArExchangeItem();
            BeanUtils.copyProperties(arExchangeItemVO, arExchangeItem);
            arExchangeItem.setExchangeId(arExchange.getId());
            arExchangeItem.setColor(arExchangeItemVO.getColor());
            arExchangeItem.setSize(arExchangeItemVO.getSize());
            arExchangeItem.setSpecifications(arExchangeItemVO.getSpecifications());

            //减库存
            ArInventory arInventory = arInventoryMapper.selectInventoryByProCode(arExchangeItemVO.getProCode());
            if (arInventory == null)
                throw new ServiceException("兑换失败,商品编码错误");
            arInventory.setInventory(arInventory.getInventory() - arExchangeItemVO.getProductNumber());
            if (arInventory.getInventory() < 0)
                throw new ServiceException("兑换失败,库存不足", 409);
            if (arInventoryMapper.updateArInventory(arInventory) == 0)
                throw new ServiceException("兑换失败");

            //减积分
            User user = userMapper.selectUserByPkId(userId);
            if (user == null)
                throw new ServiceException("查询用户失败");
            BigDecimal subtract = user.getPoint().subtract(arExchangeItemVO.getTotalPrice());
            if (subtract.compareTo(new BigDecimal(0)) < 0)
                throw new ServiceException("兑换失败,积分不足", 409);
            UserUpdateDTO userUpdateDTO = new UserUpdateDTO();
            userUpdateDTO.setPkId(userId);
            userUpdateDTO.setPoint(subtract);
            userMapper.updateUser(userUpdateDTO);

            //出库数据
            arInventory.setId(null);
            arInventory.setInventoryFlag("2");
            arInventory.setOutboundReason("积分兑换");
            arInventory.setOutboundNumber(arExchangeItemVO.getProductNumber());
            arInventory.setUpdateBy(SecurityUtils.getUsername());
            arInventory.setUpdateTime(LocalDate.now());
            arInventory.setPlatformId(PlatformIdHolder.getPlatformId());
            if (arInventoryMapper.insertArInventory(arInventory)==0)
                throw new ServiceException("兑换失败");

            //添加兑换项
            if (arExchangeItemMapper.insertArExchangeItem(arExchangeItem) == 0)
                throw new ServiceException("兑换失败");

        }

    }
}
